<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .border {
            border-collapse: collapse;
        }

        td {
            border: 1px solid #aaa;
            padding: 10px;
        }
    </style>
</head>

<body>
    <div id="app">
        <table class="border">
            <tr v-for="(item,index) in books" :key="index">
                <td>{{ item.id }}</td>
                <td>{{ item.name }}</td>
                <td>{{ item.price }}</td>
                <td>
                    <button :disabled="disable=item.count<2" @click="subtract(item)">-</button>
                    {{ item.count }}
                    <button @click="add(item)">+</button>
                </td>
                <td><button @click="del(index)">移除书籍</button></td>
            </tr>
        </table>
        <h3 v-if="books.length>0">结算金额：{{totalCompute}}</h3>
        <h3 v-else>购物车中暂时没有书籍数据！</h3>
    </div>
    <script src="../assets/vue3.js"></script>
    <script>
        const app = Vue.createApp({
            data() {
                return {
                    books: [
                        { id: 1, name: 'Net安全', price: 44.5, count: 1 },
                        { id: 2, name: 'Web安全', price: 64, count: 1 },
                        { id: 3, name: 'Net基础', price: 38, count: 1 },
                        { id: 4, name: 'Vue学习', price: 50.1, count: 1 },
                    ]
                }
            },
            methods: {
                subtract(item) {
                    item.count--;
                },
                add(item) {
                    // this.books[id - 1].count++;
                    item.count++;
                },
                del(index) {
                    this.books.splice(index, 1); //删除数组序号为index的对象
                }
            },
            computed: {
                totalCompute() {
                    // let total = 0;
                    // // 遍历一下books，并把每一项价格统计下
                    // this.books.forEach(book => {
                    //     total += book.price * book.count;
                    // });
                    // return total;
                    // reduce：
                    // return this.books.reduce((total, book) => total + book.count * book.price, 0);
                    return this.books.reduce((total, book) => {
                        return total += book.count * book.price;
                    }, 0);
                }
            },
        });
        app.mount('#app');
    </script>
</body>

</html>